<template>
  <el-card class="content-card">
    <div class="el-descriptions__header">
      <div class="el-descriptions__title">店铺位置</div>
    </div>

    <el-form ref="formRef" :disabled="readonly" :model="formData" :rules="formRules" label-width="110px">
      <el-input v-if="!readonly" id="map-search-input" v-model="mapSearchKeyword" placeholder="请输入关键词" style="margin-bottom: .5rem">
        <template #append>
          <el-button icon="Search" @click="handleSearchLocation"/>
        </template>
      </el-input>

      <!-- 地图数据 -->
      <div id="map-container" style="margin-bottom: 1rem;"></div>

      <el-form-item label="经度：" prop="longitude">
        <el-input v-model="formData.longitude" placeholder="点击地图获取" readonly/>
      </el-form-item>
      <el-form-item label="纬度：" prop="latitude">
        <el-input v-model="formData.latitude" placeholder="点击地图获取" readonly/>
      </el-form-item>
      <el-form-item label="区域地址：" prop="region_name">
        <el-input v-model="formData.region_name" :maxlength="200" autosize placeholder="点击地图获取" readonly type="textarea"/>
      </el-form-item>
      <el-form-item label="详细地址：" prop="address">
        <el-input v-model="formData.address" :maxlength="200" :readonly="readonly" autosize placeholder="请填写详细门牌楼层地址" type="textarea"/>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { nextTick, onMounted, onUnmounted, reactive, ref } from 'vue';
import { FormInstance, FormRules } from 'element-plus';
import { ShopLocationData } from '@/api/common.ts';
import AMapLoader from '@amap/amap-jsapi-loader';
import { MAP_KEY, MAP_SECURITY_KEY } from '@/utils/constant.ts';

const formData = defineModel<ShopLocationData>({required: true});
const props = defineProps({
  readonly: {
    type: Boolean,
    default: false
  },
});

const formRef = ref<FormInstance>();
const formRules = reactive<FormRules>({
  address: [{required: true, message: '请填写店铺详细地址', trigger: 'blur'}],
  longitude: [{required: true, message: '请点击地图获取信息', trigger: 'blur'}],
  latitude: [{required: true, message: '请点击地图获取信息', trigger: 'blur'}],
  region_name: [{required: true, message: '请点击地图获取信息', trigger: 'blur'}],
});

/** 地图安全密钥设置 */
// @ts-ignore
window._AMapSecurityConfig = {
  securityJsCode: MAP_SECURITY_KEY,
};

/** 参数信息 */
const map = ref();
const mapGeocoder = ref();
const mapMarker = ref();
const mapSearchKeyword = ref('');

onMounted(async () => {
  initMap();
});

onUnmounted(() => {
  map.value?.destroy();
});

/** 地图初始化 */
const initMap = () => {
  AMapLoader.load({
    key: MAP_KEY, // 申请好的Web端开发者Key，首次调用 load 时必填
    version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
    plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.Geocoder',], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
  }).then((AMap) => {
    map.value = new AMap.Map('map-container', {
      zoom: 5,           // 初始化地图级别
      viewMode: '3D',    // 是否为3D地图模式
      resizeEnable: true
    });
    map.value.addControl(new AMap.Scale());
    map.value.addControl(new AMap.ToolBar());
    map.value.on('click', handleMapClick);
    map.value.on('complete', handleMapComplete);
    mapGeocoder.value = new AMap.Geocoder({
      // city: '010', // 城市设为北京，默认：“全国”
      // radius: 1000 // 范围，默认：500
    });
    mapMarker.value = new AMap.Marker({map: map.value});
  }).catch((e) => console.log(e));
};

/** 添加地图标记点 */
const addMapMarker = () => {
  console.log('添加地图标记点 => ');
  if (map.value && mapMarker.value) {
    // let position = [formData.value.longitude, formData.value.latitude]
    // mapMarker.value.setPosition(position)
    // map.value.setZoomAndCenter(11, position) // 设置地图中心点
    if (!isNaN(formData.value.longitude) && !isNaN(formData.value.longitude)) {
      let position = [formData.value.longitude, formData.value.latitude];
      mapMarker.value.setPosition(position);
      // map.value.setZoomAndCenter(5, position);
      map.value.add(mapMarker.value);
      nextTick(() => {
        map.value.setFitView(mapMarker.value);
      })
    }
  }
};

/** 地图点击触发*/
const handleMapClick = (e) => {
  if (props.readonly) return;
  console.log('地图点击触发 => ', e);
  formData.value.longitude = e.lnglat.lng;
  formData.value.latitude = e.lnglat.lat;
  let position = [formData.value.longitude, formData.value.latitude];
  mapMarker.value.setPosition(position);
  mapGeocoder.value.getAddress(position, handleMapGeocoderResult);
};

/** 地图加载完成触发 */
const handleMapComplete = () => {
  // console.log('地图加载完成触发 => ');
  addMapMarker();
};

/** 经纬度查询地址 */
const handleMapGeocoderResult = (status, result) => {
  console.log('经纬度查询地址 =>', status, result);
  if (status === 'complete' && result.regeocode) {
    let addressComponent = result.regeocode.addressComponent;
    formData.value.region_name = result.regeocode.formattedAddress;
    formData.value.region_code = addressComponent.adcode;
  }
};

/** 查询位置信息 */
const handleSearchLocation = () => {
  let keyword = mapSearchKeyword.value;
  if (!keyword || keyword.trim() == '') {
    return
  }
  mapGeocoder.value.getLocation(keyword, function (status, result) {
    console.log('查询位置信息 =>', status, result);
    if (status === 'complete' && result.geocodes.length) {
      let data = result.geocodes[0];
      formData.value.longitude = data.location.lng;
      formData.value.latitude = data.location.lat;
      formData.value.region_name = data.formattedAddress;
      formData.value.region_code = data.adcode;

      // 添加地图标记点
      addMapMarker();
    }
  });
};

/** 表单重置 */
const formReset = () => {
  if (!formRef.value) return
  formRef.value.resetFields()
};

/** 表单验证 */
const formValidate = () => {
  if (!formRef.value) return
  return formRef.value.validate()
};

/** 对外提供方法 */
defineExpose({formReset, formValidate, addMapMarker,});
</script>

<style lang="scss" scoped>
#map-container {
  padding: 0;
  margin: 0;
  width: 100%;
  min-height: 18rem;
}
</style>
